﻿using System;
using System.Reflection;
using System.Reflection.Emit;

namespace RuntimeHelloWorlds
{
	/// <summary>
	/// The DynamicMethod is a nice shorthand way to emit a method at runtime, without
	/// all the clutter of creating a dynamic assembly, module and type (see ReflectionEmitHelloWorld)
	/// </summary>
	public class DynamicMethodHelloWorld
	{
		public void SayHelloWorld()
		{
			DynamicMethod helloMethod = new DynamicMethod("HelloWorld", typeof(void), null);
			ILGenerator ilgen = helloMethod.GetILGenerator();

			ilgen.Emit(OpCodes.Ldstr, "Hello, World! (Dynamic Method)");

			MethodInfo methodInfo 
				= typeof(Console)
				  .GetMethod("WriteLine", new [] { typeof(string)});

			ilgen.EmitCall(OpCodes.Call, methodInfo, null);
			ilgen.Emit(OpCodes.Ret);

			Action helloDelegate = (Action)helloMethod.CreateDelegate(typeof(Action));

			helloDelegate();
		}
	}
}
